<?php
include '../../init.php';

include DIR_CORE.'mysql.php';
include DIR_CORE.'upload.php';
//var_dump($_POST);
//var_dump($_FILES['file']);
//获取接收的数据
session_start();
$name = $_SESSION['userInfo']['name'];
$nickname = trim($_POST['nickname']);
$sex = trim($_POST['sex']);
$tel = trim($_POST['tel']);
$email = trim($_POST['email']);
$remark = trim($_POST['remark']);

$file = $_FILES['file'];
$allow = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');
$path = '../../public/uploads/img';

if (!empty($file['name'])) {
    //调用函数
    $result = upload($file, $allow, $error, $path);
    //echo $result;
    //入库
    if ($result) {
        //上传成功，提取信息
        session_start();
        $name = $_SESSION['userInfo']['name'];
        //提取旧头像
        $old_sql = "select image from user where name='$name'";
        $old_result = mysqli_query($link, $old_sql);
        $old_row = mysqli_fetch_assoc($old_result);
        $old_name = $old_row['image'];
        //更新
        $sql = "update user set image='$result',sex='$sex',tel='$tel',remark='$remark',nickname='$nickname',email='$email' where name='$name'";
        $res = mysqli_query($link, $sql);
        if ($res) {
            //入库成功
            //删除旧头像
            $d = 'default.jpg';
            if ($old_name != $d) {
                unlink($path . '/' . $old_name);
                
                jump('info.php', '<h2 style="color:green;">头像上传成功！</h2>');
            } else {
                jump('info.php', '<h2 style="color:green;">头像上传成功！（首次）</h2>');
            }
        } else {
            //入库失败
            
            echo '<h2 style="color:red;">发生未知错误，入库失败！</h2>';
        }
    } else {
        //上传失败
        
        echo '<h2 style="color:red;">发生未知错误，上传失败！</h2>';
    }
} else {
    //更新
    $sql = "update user set sex='$sex',tel='$tel',remark='$remark',nickname='$nickname',email='$email' where name='$name'";
    //echo $sql;
    $res = mysqli_query($link, $sql);
    if ($res) {
        jump('info.php', '<h2 style="color:green;">完善成功</h2>');
    } else {
        echo '<h2 style="color:red;">完善失败！</h2>';
    }
}
